package cc.geguo;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.crypto.Cipher;

public class CertificateUtil {

	public static PrivateKey getPrivateKeyFromKeyStore(String keystorePath, String alias, String password) throws Exception{
		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		InputStream keystoreFile=new FileInputStream(keystorePath);
		keyStore.load(keystoreFile,password.toCharArray());// 加载证书文件
		PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias,password.toCharArray());
		keystoreFile.close();
		return privateKey;
	}

	public static PublicKey getPublicKeyFromCertificate(String certificatePath) throws Exception{
		CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
		FileInputStream cerFile = new FileInputStream(certificatePath);
		Certificate certificate = certificateFactory.generateCertificate(cerFile);
		PublicKey publicKey = certificate.getPublicKey();
		cerFile.close();
		return publicKey;
	}

	public static byte[] encrypt(byte[] bytes, PublicKey publicKey) throws Exception{
		Cipher instance = Cipher.getInstance(publicKey.getAlgorithm());
		instance.init(Cipher.ENCRYPT_MODE,publicKey);
		return instance.doFinal(bytes);
	}

	public static byte[] decrypt(byte[] cipherData, PrivateKey privateKey) throws Exception{
		Cipher cipherUtil = Cipher.getInstance(privateKey.getAlgorithm());
		cipherUtil.init(Cipher.DECRYPT_MODE,privateKey);
		return cipherUtil.doFinal(cipherData);

	}
}
